package com.xm.clj.underserver.utils;

import com.alibaba.fastjson.JSON;
import com.xm.clj.underserver.bean.GetMessage;
import com.xm.clj.underserver.bean.StartInfo;
import com.xm.clj.underserver.service.GameService;
import com.xm.clj.underserver.serviceImpl.GameServiceImpl;
import com.xm.clj.underserver.webSocket.OneToManyWebSocket;
import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class AsyncTask {

    GameService gameService = new GameServiceImpl();

    @Async("taskExecutor")
    public void readInfo(String message,String userId){
        JSONObject jsonObject = JSONObject.fromObject(message);
        GetMessage getMessage = (GetMessage) JSONObject.toBean(jsonObject,GetMessage.class);
        switch (getMessage.getId()){
            case "2":
                // 投票信息
                voteResponse(getMessage);
                break;
            case "6":
                // 玩家聊天
                chatResponse(getMessage);
                break;
        }
    }

    @Async("taskExecutor")
    public void tesTask(int i){
        System.out.println(Thread.currentThread().getName()+"-----"+i);
    }

    @Async("taskExecutor")
    public void stringTask(String str){

        System.out.println(Thread.currentThread().getName()+"   mes: "+str);
    }


    public void voteResponse(GetMessage message){
        // 分析投票消息，
        String fromId = message.getFrom();
        String voteInfo = message.getMes();
        // 统计
        Map<String,Object> res = DBUtils.db_findUserInfo(fromId);
        String room = (String) res.get("roomId");
        List<String> votes = new ArrayList<>();
        System.out.println("room: "+room);
        if (!OneToManyWebSocket.curVote.containsKey(room)){
            votes.add(voteInfo);
        }
        else{
            votes = OneToManyWebSocket.curVote.get(room);
            votes.add(voteInfo);
            if (votes.size()==OneToManyWebSocket.curPlayers.get(room)){
                // 产生当前回合结果
                String curVoteRes = voteRes(votes,room);


            }
        }
        OneToManyWebSocket.curVote.put(room,votes);

        // 显示投票信息,发送给除投票者外所有玩家（当前房间）
        // TODO  将玩家id与序号对应
        OneToManyWebSocket.sendRoomVoteMessage(voteInfo,fromId);
        // 记录投票信息并统计



        // 返回消息
    }

    public void chatResponse(GetMessage message){
        OneToManyWebSocket.sendChatToOther(message,message.getFrom(),message.getTo());
    }

    private static String voteRes(List<String> votes, String room){
        boolean mflag = false;
        int[] res = new int[votes.size()+1];
        for (String vote:votes){
            res[Integer.parseInt(vote)]++;
        }
        int max = 1;
        for (int i=1;i<res.length;i++){
            if (res[i]>res[max]){
                max = i;
                mflag = false;
            }
            if (res[i]==res[max]){
                mflag = true;
            }
        }
        if (mflag){
            // 重新投票
            GetMessage message = new GetMessage();
            message.setId("10");
            message.setMes("请重新投票");
            message.setFrom("0");
            OneToManyWebSocket.sendToAll(JSON.toJSONString(message),room);
            return "";
        }
        else {
            // 淘汰
            int resnum = OneToManyWebSocket.curPlayers.get(room) - 1;
            OneToManyWebSocket.curPlayers.put(room, resnum);
            String flag = "false";
            List<String> unders = OneToManyWebSocket.roomUnder.get(room);
            if (unders.contains("" + max)) {
                unders.remove("" + max);
                if (unders.isEmpty()) {
                    // 平民胜利
                    GetMessage finalMessage = new GetMessage();
                    finalMessage.setId("4");
                    finalMessage.setMes("success");
                    OneToManyWebSocket.sendToAll(JSON.toJSONString(finalMessage), room);
                    sendWordsToAll(room);
                }
                // 投票正确
                flag = "true";
            }
            if (OneToManyWebSocket.curPlayers.get(room) == unders.size()) {
                // 卧底获胜
                GetMessage finalMessage = new GetMessage();
                finalMessage.setId("4");
                finalMessage.setMes("fail");
                OneToManyWebSocket.sendToAll(JSON.toJSONString(finalMessage), room);
                sendWordsToAll(room);
            }
            // 投票错误
            GetMessage getMessage = new GetMessage();
            getMessage.setId("3");
            getMessage.setMes(flag);
            getMessage.setTo("" + max);
            return "" + max;
        }
    }

    private static void sendWordsToAll(String room) {
        List<String> curWords = OneToManyWebSocket.roomWords.get(room);
        String res = "平民： "+curWords.get(0)+"  卧底："+curWords.get(1);
        GetMessage getMessage = new GetMessage();
        getMessage.setId("10");
        getMessage.setFrom("0");
        getMessage.setMes(res);
        OneToManyWebSocket.sendToAll(JSON.toJSONString(res),room);
    }


    @Async("taskExecutor")
    public void startGameTask(StartInfo startInfo){
        gameService.startAGame(startInfo);
        System.out.println(Thread.currentThread().getName()+"   开始创建游戏");
    }
}
